package com.evan.wj.controller;

import com.evan.wj.result.Result;
import com.evan.wj.result.ResultFactory;
import com.evan.wj.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.util.HtmlUtils;

import com.evan.wj.pojo.User;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.ConstraintViolationException;
import java.util.Objects;

@Controller
public class LoginController {

    @Autowired
    public UserService userService;

    @CrossOrigin
    @PostMapping(value = "api/login")
    @ResponseBody
    public Result login(@RequestBody User requestUser, HttpServletRequest request) {

        String username = requestUser.getUsername();

        User user = userService.get(username, requestUser.getPassword());
        try {
            if (null==user) {
                return ResultFactory.buildFailResult("账号密码错误");
            }else if (!user.getEnabled()){
                return ResultFactory.buildFailResult("该用户已被禁用");
            }
            else {
                request.getSession().setAttribute("user", user);
                return ResultFactory.buildSuccessResult(username);
            }
        }catch (Exception e){
            System.out.println(e.getMessage());
        }
        return ResultFactory.buildFailResult("未知错误");
    }

    @ResponseBody
    @PostMapping("/api/register")
    public Result register(@RequestBody User user){

        try {
            int status = userService.register(user);
            switch (status){
                case 0:
                    return ResultFactory.buildFailResult("用户名和密码不能为空");
                case 1:
                    return ResultFactory.buildSuccessResult("注册成功");
                case 2:
                    return ResultFactory.buildFailResult("用户名重复");
            }
        }catch (ConstraintViolationException e){
            return ResultFactory.buildFailResult("邮箱错误");
        }catch (Exception e){
            return ResultFactory.buildFailResult("未知错误,联系管理员");
        }
        return ResultFactory.buildFailResult("未知错误");
    }


    @ResponseBody
    @GetMapping("api/logout")
    public Result logout(HttpSession session) {
//        Subject subject = SecurityUtils.getSubject();
//        subject.logout();
        session = null;
//        this.principals = null;
//        this.authenticated = false;
        String message = "成功登出";
        return ResultFactory.buildSuccessResult(message);

    }



}

